import { Card, message, Row, Col, Space, Modal, Form, Input, Button, Descriptions } from 'antd';
import { history } from 'umi';
import ProForm, { ProFormText, ProFormUploadButton, ProFormTextArea } from '@ant-design/pro-form';
import { useRequest } from 'umi';
import type { FC } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { useState } from 'react';
import { fakeSubmitForm, queryAuthHospitalDetail, update, approveHospital } from './service';

const { TextArea } = Input;
const BasicForm: FC<Record<string, any>> = () => {
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [proform] = Form.useForm();
  const { run } = useRequest(fakeSubmitForm, {
    manual: true,
    onSuccess: () => {
      message.success('提交成功');
    },
  });

  const { id } = history.location.query;

  const { data } = useRequest(() => {
    if (id) {
      return queryAuthHospitalDetail({ id: id });
    }
  });

  // const { data, loading } = useRequest(() => {
  //   if (history.location.query.id) {
  //     return queryAuthHospitalDetail(history.location.query);
  //   }
  // });

  const approveAgree = async (item: Object) => {
    proform
      .validateFields()
      .then((values) => {
        console.log('values', values);
        item.sort = values.sort;
        approve(item);
      })
      .catch((info) => {
        console.log('Validate Failed:', info);
      });
  };

  const approve = async (item: Object) => {
    const hide = message.loading('正在处理');
    item.id = id;
    item.hospitalId = data.hospitalId;
    // item.sort = item.sort;
    try {
      const response = await approveHospital(item);
      if (response.code == 200) {
        message.success('处理成功,即将跳转列表页面');
        if (open) {
          setOpen(false);
        }
        history.push('/hospital/authList');
      } else {
        message.error('处理失败!');
      }
      hide();
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  const onFinish = async (values: Record<string, any>) => {
    console.log('values11', values);
    if (values.upload[0].response) {
      values.logo = values.upload[0].response.data.url;
    }
    if (values.upload[0].response) {
      values.logo = values.upload[0].response.data.url;
    }
    if (values.upload[0].response) {
      values.logo = values.upload[0].response.data.url;
    }
    values.provinceName = values.dz.province.label;
    values.provinceCode = values.dz.province.value;
    values.cityName = values.dz.city.label;
    values.cityCode = values.dz.city.value;
    values.areaName = values.dz.district.label;
    values.areaCode = values.dz.district.value;
    values.addressDetail = values.dz.detailed;
    console.log('values', values);
    if (history.location.query.id) {
      values.id = history.location.query.id;
      try {
        const response = await update(values);
        if (response.code == 200) {
          message.success('修改成功');
        } else {
          message.error('修改失败!');
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      run(values);
    }
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProForm
          hideRequiredMark
          style={{ margin: 'auto', marginTop: 8 }}
          name="basic"
          form={proform}
          layout="horizontal"
          // initialValues={data}
          // onFinish={onFinish}
          {...formItemLayout}
          request={async () => {
            if (history.location.query.id) {
              return queryAuthHospitalDetail(history.location.query).then(({ data }) => {
                // let diseaseIds = [];
                // for (var i = 0; i < data.diseaseRelationList.length; i++) {
                //   diseaseIds.push(data.diseaseRelationList[i].diseaseId);
                // }
                // data.diseaseIds = diseaseIds;
                // data.addUserType = data.addUserType + '';
                console.log('data', data);
                // const dz = {};
                // dz.address = data.addressDetail;
                // const province = {};
                // province.label = data.provinceName;
                // province.value = data.provinceCode;
                // dz.province = province;

                // const city = {};
                // city.label = data.cityName;
                // city.value = data.cityCode;
                // dz.city = city;

                // const district = {};
                // district.label = data.areaName;
                // district.value = data.areaCode;
                // dz.district = district;
                // dz.detailed = data.addressDetail;
                // data.dz = dz;
                if (data.logo) {
                  data.upload = [
                    {
                      uid: '1',
                      name: 'icon',
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + data.logo,
                    },
                  ];
                }
                if (data.businessLicense) {
                  data.businessLicense = [
                    {
                      uid: '1',
                      name: 'icon',
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + data.businessLicense,
                    },
                  ];
                }
                if (data.insLicenseCert) {
                  data.insLicenseCert = [
                    {
                      uid: '1',
                      name: 'icon',
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + data.insLicenseCert,
                    },
                  ];
                }
                data.businessStatus = data.businessStatus + '';
                return data;
              });
            } else {
              return {};
            }
          }}
          submitter={{
            render: (props, doms) => {
              return null;
            },
          }}
        >
          <ProFormText
            width="md"
            label="医院名称"
            name="name"
            disabled
            // rules={[
            //   {
            //     required: true,
            //     message: '请输入医院名称',
            //   },
            // ]}
            placeholder="请输入医院名称"
          />
          <ProFormUploadButton
            name="upload"
            label="医院logo"
            disabled
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
          />
          <ProFormTextArea name="intro" label="医院简介" placeholder="请输入医院简介" disabled />
          <ProFormTextArea
            name="visitInfo"
            label="门诊时间"
            placeholder="请输入门诊时间"
            disabled
          />
          <ProFormTextArea
            name="registration"
            label="挂号攻略"
            placeholder="请输入医院简介"
            disabled
          />
          <ProFormUploadButton
            name="businessLicense"
            label="营业执照"
            max={1}
            disabled
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
          />
          <ProFormUploadButton
            name="insLicenseCert"
            label="医疗机构执业许可证"
            disabled
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
          />

          {/* {data && data.status == 0 ? (
            <ProFormText
              width="md"
              label="医院排序"
              name="sort"
              rules={[
                {
                  required: false,
                  message: '请输入0-100的整数，数值越小在医院列表内越靠前显示',
                },
              ]}
              placeholder="请输入0-100的整数，数值越小在医院列表内越靠前显示"
            />
          ) : null}
         <ProForm.Item
            name="dz"
            label="医院地址"
            rules={[
              {
                required: true,
                message: '请输入医院地址',
              },
            ]}
            valuePropName="checked"
          >
            <Address />
          </ProForm.Item>
          <ProFormRadio.Group
            request={async () => {
              const params = { dictCode: 'grade' };
              return queryDictList(params).then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.itemName,
                    value: item.itemName,
                  };
                });
              });
            }}
            label="医院等级"
            name="grade"
          />
          <ProFormRadio.Group
            request={async () => {
              const params = { dictCode: 'operationNature' };
              return queryDictList(params).then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.itemName,
                    value: item.itemName,
                  };
                });
              });
            }}
            label="运营性质"
            name="operationNature"
          />
          <ProFormRadio.Group
            request={async () => {
              const params = { dictCode: 'professionalNature' };
              return queryDictList(params).then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.itemName,
                    value: item.itemName,
                  };
                });
              });
            }}
            label="专业性质"
            name="professionalNature"
          />

          <ProFormTextArea name="excellentDept" label="特色科室" placeholder="请输入特色科室" />

          <ProFormRadio.Group
            options={[
              {
                value: '0',
                label: '营业',
              },
              {
                value: '1',
                label: '歇业',
              },
            ]}
            label="营业状态"
            name="businessStatus"
          /> */}
          {/* <Descriptions
            column={1}
            labelStyle={{
              // color: '#787A7D',
              width: '150px',
              marginRight: '10px',
              display: 'block',
              textAlign: 'right',
            }}
          > */}
          {data && data.status == 1 ? (
            <ProForm.Item name="statusName" label="审核状态">
              审核通过
            </ProForm.Item>
          ) : null}
          {data && data.status == 2 ? (
            <ProForm.Item name="statusName" label="审核状态">
              审核未通过
            </ProForm.Item>
          ) : null}
          {data && data.status == 2 ? (
            <ProForm.Item name="statusName" label="审核状态">
              {data ? data.failReason : ''}
            </ProForm.Item>
          ) : null}
          {/* /</Descriptions> */}
          {data && data.status == 0 ? (
            <Row>
              <Col span={14} offset={2}>
                <Space>
                  {' '}
                  <Button
                    type="primary"
                    key=""
                    onClick={() => {
                      let item = { status: 1 };
                      approveAgree(item);
                    }}
                  >
                    审核通过
                  </Button>
                  <Button
                    key="reject"
                    onClick={() => {
                      setOpen(true);
                    }}
                  >
                    审核不通过
                  </Button>
                   <Button
                    key="reject"
                    onClick={() => {
                     let item = { status: 3 };
                      approveAgree(item);
                    }}
                  >
                    审核中止
                  </Button>
                </Space>
              </Col>
            </Row>
          ) : null}
        </ProForm>
      </Card>
      <Modal
        open={open}
        title="请输入审核不通过原因"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setOpen(false);
        }}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              values.status = 2;
              approve(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item name="failReason" label="">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default BasicForm;
